<?php
namespace Admin\Controller;
use Lib\Api\AgentApi;
use Lib\Api\AgentBelongApi;
use Lib\Api\AgentCommissionSetApi;
use Lib\Api\AgentSettlementApi;
use Lib\Api\GameTypeApi;
use Lib\Api\UserApi;
use Lib\Api\UserBelongApi;
use Think\Controller;
use Think\Model;
class AgentController extends Controller {
    private $modelName = 'Agent';

    public function index(){
        $this->assign('level', 4);
        $this->display();
    }

    public function tolist() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $organization_id = session('admin_id');
        $level = $_POST['level'];

        $AGENTCONFIG = C('AGENTCONFIG');
        $field = "a.id, a.name, a.mobile_phone, a.balance, a.state, a.audit_state";

        // $where["b.level"] = $level;
        $where["b.organization_id"] = $organization_id;
        // $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $left = 'left join fs_agent_belong b on b.agent_id = a.id and b.state = 1';

        if ($level > 0) {
            for($i=1; $i<$level; $i++) {
                $field .= ',ifnull(o'.$i.'.name, "--") as '.$AGENTCONFIG[$i]['field'];
                $left .= ' left join fs_agent_belong ob'.$i.' on ob'.$i.'.agent_id = a.id and ob'.$i.'.state = 1 and ob'.$i.'.organization_level = '.$i;
                $left .= ' left join fs_organization o'.$i.' on o'.$i.'.id = ob'.$i.'.organization_id';
            }
        }

        $list = AgentApi::getList($where, $left, $page_num, $page_size, $field, 'a.datetime desc');
        $total = AgentApi::getTotal($where, $left);
        $user_list = pageHelper($page_size, $page_num, $list, $total);
        $user_list['setting'] = $AGENTCONFIG[$level]['setting'];
        $user_list['type'] = $AGENTCONFIG[$level]['type'];
        $rel['data'] = $user_list;
        $rel['sum_balance'] = AgentApi::getSum($where, "a.balance", $left);
        $this->ajaxReturn($rel);
    }

    // 审核经纪人
    public function changeAuditState() {
        $model = M($this->modelName);
        $state = AgentApi::save($model->create($_POST, Model::MODEL_UPDATE));
        if ($state == 1) {
            if ($_POST['audit_state'] == 1) {
                // 获取账户信息
                $agent = AgentApi::getInfo(array("a.id"=>$_POST['id']), "", "a.id, a.name");
                // 获取游戏类型
                $game_list = GameTypeApi::getList(array(), 0, 999999, 'id, show_name, open_time');
                if (!empty($game_list)) {
                    $organizationCommissionSet_arr = array();
                    for ($i=0; $i<count($game_list); $i++) {
                        // 添加经纪人默认返佣
                        $userCommissionSet['agent_id'] = $agent['id'];
                        $userCommissionSet['game_name'] = $game_list[$i]['show_name'];
                        $userCommissionSet['game_type'] = $game_list[$i]['id'];
                        $userCommissionSet['commission_ratio'] = 0;
                        $userCommissionSet['take_effect_time'] = date('Y-m-d') . ' '. $game_list[$i]['open_time'];
                        $userCommissionSet['datetime'] = date('Y-m-d H:i:s');
                        array_push($organizationCommissionSet_arr, $userCommissionSet);
                    }
                    if (count($organizationCommissionSet_arr) > 0) {
                        AgentCommissionSetApi::addAll($organizationCommissionSet_arr);
                    }
                }

                // 添加经纪人结算数据
                $begin_time = date("Y-m-d H:i:s");
                $end_time = date("Y-m-d H:i:s",strtotime($begin_time."+1 day"));
                $agentSettlement['agent_id'] = $agent['id'];
                $agentSettlement['sys_total_fee'] = 0;
                $agentSettlement['total_fee'] = 0;
                $agentSettlement['settlement_money'] = 0;
                $agentSettlement['state'] = 2;
                $agentSettlement['begin_time'] = $begin_time;
                $agentSettlement['end_time'] = $end_time;
                AgentSettlementApi::add($agentSettlement);

                $rel['id'] = $agent['id'];
                $rel['name'] = $agent['name'];
                $rel['msg'] = '经纪人申请已通过，请为经纪人设置返佣';
            } else {
                $rel['msg'] = '经纪人申请已驳回';
            }
        } else {
            $rel['msg'] = '设置失败';
        }
        $rel['code'] = $state;
        $this->ajaxReturn($rel);
    }

    // 更改经纪人状态
    public function changeState() {
        $model = M($this->modelName);
        $this->ajaxReturn(AgentApi::save($model->create($_POST, Model::MODEL_UPDATE)));
    }

    // 更改经纪人归属
    public function changeBelong() {
        $org_level = $_POST['org_level'];
        $org_id = $_POST['org_id'];
        $id = $_POST['agent_id'];
        $data["state"] = 2;
        AgentBelongApi::saveByCondition(array("agent_id"=>$id, "organization_level"=>$org_level), $data);
        $agentBelong["agent_id"] = $id;
        $agentBelong["organization_id"] = $org_id;
        $agentBelong["organization_level"] = $org_level;
        $agentBelong["state"] = 1;
        $agentBelong["datetime"] = date("Y-m-d H:i:s");
        $s = AgentBelongApi::add($agentBelong);
        if ($s) {
            // 更改经纪人下所有用户的归属
            $uses = UserApi::getListAllByCondition(array("recommend_id"=>$id),"","id");
            if (!empty($uses)) {
                for ($i=0; $i<count($uses); $i++) {
                    UserBelongApi::saveByCondition(array("user_id"=>$uses[$i]["id"], "organization_level"=>$org_level), $data);
                    $userBelong["user_id"] = $uses[$i]["id"];
                    $userBelong["organization_id"] = $org_id;
                    $userBelong["organization_level"] = $org_level;
                    $userBelong["state"] = 1;
                    $userBelong["datetime"] = date("Y-m-d H:i:s");
                    UserBelongApi::add($userBelong);
                }
            }
            $rel['code'] = 1;
        } else {
            $rel['code'] = -1;
        }
        $this->ajaxReturn($rel);
    }

    // 获取经纪人返佣设置
    public function getAgentCommissionSet() {
        $agent_id = $_POST['agent_id'];
        $game_list = GameTypeApi::getList(array("state" => 1), 1, 99999, "*", "sort asc");
        $agentCommissionSet_list = AgentCommissionSetApi::getAllListByCondition(array("a.agent_id" => $agent_id), "", "a.*", "a.take_effect_time desc");
        // var_dump($agentCommissionSet_list);
        $arr = array();
        for ($i=0;$i<count($game_list); $i++) {
            $index = 0;
            $temp_set_list = array();
            for ($j=0;$j<count($agentCommissionSet_list); $j++) {
                if ($index == 2) break;
                // if (strcasecmp($game_list[$i]['game_type'], $agentCommissionSet_list[$j]['game_type']) == 0) {
                if (strcasecmp($game_list[$i]['id'], $agentCommissionSet_list[$j]['game_type']) == 0) {
                    $index++;
                    array_push($temp_set_list, $agentCommissionSet_list[$j]);
                }
            }
            $agentCommissionSet['name'] = $game_list[$i]['show_name'];
            $agentCommissionSet['type'] = $game_list[$i]['id'];
            $agentCommissionSet['open_time'] = $game_list[$i]['open_time'];
            if (count($temp_set_list) == 2) {
                $c_date = date('Y-m-d H:i:s');
                if(strtotime($c_date) > strtotime($temp_set_list[0]['take_effect_time'])) {
                    $agentCommissionSet['id'] = 0;
                    $agentCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $agentCommissionSet['is_take_effect'] = 1;
                    $agentCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                    $agentCommissionSet['take_effect_time'] = '';
                    $agentCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];
                } else if(strtotime($c_date) > strtotime($temp_set_list[1]['take_effect_time'])) {
                    $agentCommissionSet['id'] = $temp_set_list[0]['id'];
                    $agentCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[1]['commission_ratio']);
                    $agentCommissionSet['is_take_effect'] = 0;
                    $agentCommissionSet['new_commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $agentCommissionSet['take_effect_time'] = $temp_set_list[0]['take_effect_time'];
                    $agentCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];
                }
            } else if (count($temp_set_list) == 1) {
                $agentCommissionSet['id'] = 0;
                $agentCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                $agentCommissionSet['is_take_effect'] = 1;
                $agentCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                $agentCommissionSet['take_effect_time'] = '';
                $agentCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);

                $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];

            } else {
                $agentCommissionSet['id'] = 0;
                $agentCommissionSet['commission_ratio'] = '--';
                $agentCommissionSet['is_take_effect'] = 1;
                $agentCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                $agentCommissionSet['take_effect_time'] = '';
                $agentCommissionSet['value'] = sprintf("%.2f",0);

                $ajaxdata['last_update_time'] = "--";
            }
            array_push($arr, $agentCommissionSet);
        }

        $ajaxdata['agentCommissionSet'] = $arr;

        $this->ajaxReturn($ajaxdata);
    }

    // 设置用户返佣
    public function addAgentCommissionSet() {
        $agent_id = $_POST['agent_id'];
        $agentCommissionSet = $_POST['agentCommissionSet'];

        if (!empty($agentCommissionSet)) {
            $add_agentCommissionSet_arr = array();
            $isUp = false;
            $sql = "UPDATE fs_agent_commission_set SET datetime=now(), commission_ratio = CASE id ";
            $ids = array();
            for ($i=0; $i<count($agentCommissionSet); $i++) {
                $value = 0;
                if ($agentCommissionSet[$i]['value'] > 0) {
                    $value = $agentCommissionSet[$i]['value'];
                }
                if ($agentCommissionSet[$i]['id'] == 0) {
				
                    $obj['agent_id'] = $agent_id;
                    $obj['game_name'] = $agentCommissionSet[$i]['game_name'];
                    $obj['game_type'] = $agentCommissionSet[$i]['game_type'];
                    $obj['commission_ratio'] = sprintf("%.2f",$value);
                    /*$obj['take_effect_time'] = date('Y-m-d',strtotime('+1 day')) . ' '. $agentCommissionSet[$i]['open_time'];*/
					     $obj['take_effect_time'] = date('Y-m-d',strtotime('+1 day')) . ' '. $agentCommissionSet[$i]['open_time'];
           
					$obj['datetime'] = date('Y-m-d H:i:s');
                    array_push($add_agentCommissionSet_arr, $obj);
                } else {
                    $isUp = true;
                    array_push($ids, $agentCommissionSet[$i]['id']);
                    $sql .= sprintf("WHEN %d THEN %.2f ", $agentCommissionSet[$i]['id'], $value);
                }
            }

            $sql .= "END WHERE id IN (".implode(',', $ids).")";
            if ($isUp == true) {
                $model = new \Think\Model();
                $model->execute($sql);
            }

            if (count($add_agentCommissionSet_arr) > 0) {
                AgentCommissionSetApi::addAll($add_agentCommissionSet_arr);
            }
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = "返佣设置成功，该设置会在下个交易日生效";
        } else {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = "返佣设置失败";
        }
        $this->ajaxReturn($ajaxdata);
    }

    public function select_search() {
        $keyword = $_POST['keyword'];

        if ($_POST['organization_ids'] != "") {
            $organization_id = $_POST['organization_ids'];
        } else {
            $organization_id = session('admin_id');
        }


        $map['a.name']  = array('like', '%'.$keyword.'%');
        $map['a.mobile_phone']  = array('like','%'.$keyword.'%');
        $map['_logic'] = 'or';
        $where['_complex'] = $map;

        $where["b.organization_id"] = array("in", $organization_id);
        $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $where["a.audit_state"] = array("eq", 1);

        $left = 'left join fs_agent_belong b on b.agent_id = a.id';
        $list = AgentApi::getListByCondition($where, $left, "a.id, a.name, a.mobile_phone");
        $rel['list'] = $list;
        $this->ajaxReturn($rel);
    }


    public function toSelectList() {
        $organization_id = $_POST['organization_id'];
        $organization_level = session("admin_level");
        $user_id = $_POST['user_id'];
        if ($organization_id > 0) {
                $where["b.organization_id"] = $organization_id;
        } else {
            $organization = UserBelongApi::getUserBelongOrgByCondition(array("a.user_id"=>$user_id, "a.state"=>1, "a.organization_level"=>$organization_level),"left join fs_organization b on b.id = a.organization_id", "b.id");
            $where["b.organization_id"] = $organization["id"];
        }

        $where['DATE_FORMAT(b.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $where["a.audit_state"] = array("eq", 1);
        $where["b.state"] = array("eq", 1);
        $left = 'left join fs_agent_belong b on b.agent_id = a.id and b.state = 1';
        $list = AgentApi::getListByCondition($where, $left, "a.id, a.name");
        $rel['list'] = $list;
        $this->ajaxReturn($rel);
    }
}